package com.uchonor.api.core.service;

import com.uchonor.api.core.entity.DatasourceConfig;
import com.uchonor.api.core.mapper.DatasourceConfigMapper;
import com.uchonor.olight.agent.annotation.Inject;
import com.uchonor.olight.agent.annotation.Service;
import com.uchonor.olight.agent.annotation.db.DBTransactional;
import com.uchonor.olight.agent.module.db.BaseServiceImpl;
import com.uchonor.olight.agent.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.ssssssss.magicapi.datasource.model.DataSourceInfo;

import java.util.Map;

@Service
public class DatasourceConfigService extends BaseServiceImpl<DatasourceConfigMapper,DatasourceConfig> {
    @Inject
    private ResourceService resourceService;

    @DBTransactional
    public String saveDatasourceConfig(DatasourceConfig datasourceConfig){
        this.save(datasourceConfig);
        DataSourceInfo dataSourceInfo = new DataSourceInfo();
        dataSourceInfo.setKey(datasourceConfig.getDatasourceCode());
        dataSourceInfo.setUsername(datasourceConfig.getDatasourceUsername());
        dataSourceInfo.setPassword(datasourceConfig.getDatasourcePassword());
        dataSourceInfo.setType(datasourceConfig.getDatasourcePoolClass());
        dataSourceInfo.setUrl(datasourceConfig.getDatasourceJdbcUrl());
        dataSourceInfo.setMaxRows(datasourceConfig.getDatasourceResultMaxRows());
        dataSourceInfo.setDriverClassName(datasourceConfig.getDatasourceJdbcDriverClass());
        dataSourceInfo.setId(datasourceConfig.getDatasourceId());
        dataSourceInfo.setGroupId("datasource:0");
        dataSourceInfo.setName(datasourceConfig.getDatasourceName());
        dataSourceInfo.setCreateBy(datasourceConfig.getCreateUser());
        dataSourceInfo.setUpdateBy(datasourceConfig.getUpdateUser());
        dataSourceInfo.setCreateTime(datasourceConfig.getCreateTime()!=null?datasourceConfig.getCreateTime().getTime():null);
        dataSourceInfo.setUpdateTime(datasourceConfig.getUpdateTime()!=null?datasourceConfig.getUpdateTime().getTime():null);
        if(StringUtils.isNotBlank(datasourceConfig.getDatasourceOtherConfig())) {
            dataSourceInfo.setProperties(JsonUtils.parseObject(datasourceConfig.getDatasourceOtherConfig(), Map.class));
        }
        resourceService.saveFolder(dataSourceInfo);
        return datasourceConfig.getDatasourceId();
    }

    @DBTransactional
    public void deleteDatasourceConfig(String datasourceConfigId){
        this.removeById(datasourceConfigId);
        resourceService.delete(datasourceConfigId);
    }
}
